package com.wd.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DateUtil {

	private static Log log = LogFactory.getLog(DateUtil.class);

	private static SimpleDateFormat defaultFormat = new SimpleDateFormat(
			"yyyyMMdd HH:mm:ss");

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyyMMdd");

	public static String getCurrentFullDateString() {

		String date = defaultFormat
				.format(new Date(System.currentTimeMillis()));
		return date;
	}

	public static String getCurrentDateString() {

		String date = dateFormat.format(new Date(System.currentTimeMillis()));
		return date;
	}

	public static String getYesterdayDateString(String format) {
		SimpleDateFormat formatDate = new SimpleDateFormat(format);
		Calendar calendar = new GregorianCalendar();
		calendar.add(Calendar.DAY_OF_WEEK, -1);
		String date = formatDate.format(calendar.getTime());
		return date;
	}

	/**
	 * 
	 * @param interval
	 *            , minutes
	 * @param lastTime
	 *            , string
	 * @return true if larger, otherwise false.
	 */
	public static boolean isLargerThanIntervalMinsFromNow(int interval,
			String lastTime) {
		if (!StringUtil.isValidString(lastTime)) {
			log.info("Invalid lastTime : " + lastTime);
			return true;
		}
		long now = System.currentTimeMillis();
		long last = -1;
		try {
			Date date = defaultFormat.parse(lastTime);
			last = date.getTime();
		} catch (ParseException e) {
			log.error("", e);
		}

		long intervalSecs = interval * 60 * 1000;

		if ((now - last) >= intervalSecs) {
			return true;
		}

		return false;
	}

	public static Date getDateFromString(String s){
		if(s == null || "".equals(s)){
			return null;
		}
		Date date = null;
		try {
			date = defaultFormat.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
		return date;
	}
	
	public static Date getDateFromStringAndFormat(String s,String format){
		if(format == null || "".equals(format)){
			return null;
		}
		if(s == null || "".equals(s)){
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = sdf.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
		return date;
	}
	
	public static void main(String args[]) {
		String lastTime = "20090223 19:20:00";
		int interval = 6;
		System.out.println(isLargerThanIntervalMinsFromNow(interval, lastTime));

		System.out.println(getCurrentDateString());
		
		System.out.println(getYesterdayDateString("yyyyMMdd"));
		
		System.out.println(DateUtil.getDateFromStringAndFormat("2009-08-24 11:11:11","yyyy-MM-dd HH:mm:ss"));

	}

}
